package com.ui.basic.listener;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.springframework.web.context.WebApplicationContext;

import com.common.basic.util.Globals;

public class BaseActionListener implements ServletContextListener,
		HttpSessionListener {
	private static final transient org.apache.commons.logging.Log LOGGER = org.apache.commons.logging.LogFactory
			.getLog(BaseActionListener.class);
	
	private Map<String, UserStream> userstreams = Collections.synchronizedMap(new HashMap<String, UserStream>());
	private Map<String, HttpSession> activeUsers = Collections.synchronizedMap(new HashMap<String, HttpSession>());
	private WebApplicationContext springContext;
	
	public BaseActionListener() {
		LOGGER.info("Constructor Action listener created");
	}

	public void contextDestroyed(ServletContextEvent arg0) {
		LOGGER.info("ServletContext destroyed");
		springContext = null;

	}

	public void contextInitialized(ServletContextEvent arg0) {
		LOGGER.info("ServletContext Initialised");
		springContext = (WebApplicationContext) arg0.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		arg0.getServletContext().setAttribute(Globals.USERSTREAMS, userstreams);
		arg0.getServletContext().setAttribute(Globals.ACTIVEUSERS, activeUsers);
	}

	public void sessionCreated(HttpSessionEvent arg0) {
        HttpSession session = arg0.getSession();
        LOGGER.info("Session created : " + session.getId());
        
        UserStream userstream = new UserStream();
        session.setAttribute(Globals.USERSTREAM, userstream);
        userstreams.put(session.getId(), userstream);
        
        activeUsers.put(session.getId(), session);
	}

	public void sessionDestroyed(HttpSessionEvent arg0) {
        HttpSession session = arg0.getSession();
        LOGGER.info("Session destroyed : " + session.getId());
        try {
            userstreams.remove(session.getId());
            activeUsers.remove(session.getId());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
	}

}
